package cn.sxw.ld.common.filter;

import cn.sxw.ld.common.dto.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName:LoginCheckFilter
 * Package:cn.sjxy.graduation.common.filter
 * Description: 登录检查
 *
 * @Date:2023/2/23 21:14
 * @Author:SXW
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    /**
     * 专门用于路径比较的，路径匹配器
     */
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 过滤需求：只是过滤来自登录的请求，静态资源访问请求不过滤
     * <p>
     * 实现：
     * 1. 获取本次请求的 uri
     * 2. 判断本次请求是否需要处理，不需要则直接放行
     * 3. 判断登录状态，若登录则放行
     * 4. 未登录则提示未登录，跳转页面
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // {} 为占位符，可以动态获取 "," 后的的参数放到该位置
        // /* 1. 获取请求路径 */
        String requestURI = request.getRequestURI();

        /* 2. 判断是否需要处理 */
        // 2.1 定义一个容器，盛放无需处理的列表
        String[] passUri = {
                // 静态资源放行
                "/backend/**",
                // 文件上传的路径
                "/common/**",
                "/scrolling/**",
                "/image/**"
        };
        // 2.2 判断路径否需要处理
        boolean check = check(passUri, requestURI);
        // 2.3 若不需要处理直接放行
        if (check) {
            filterChain.doFilter(request, response);
        }

    }

    /**
     * 路径匹配方法，检查是请求否需要放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            // 匹配结果
            if (match) {
                return true;
            }
        }
        return false;
    }

}
